'''
coding: utf-8
@Software: PyCharm
@Author: JiangDa
@File: GetLocation.py
@Time: 2023/8/22 022 13:15
@Description: 
'''

import csv
import time
import random
import pandas as pd
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait


def uni_name():
    data = pd.read_csv('java2.csv', header=0)  # 开始读取csv文件
    res = data[['公司名称', '城市']]  # 获取名称和城市
    df = res.drop_duplicates(subset=['公司名称', '城市'])  # 去除重复行
    df.to_csv('公司.csv')


# 获取经纬度
def company_info_collect():
    data = pd.read_csv('公司.csv',
                       encoding='utf-8', header=0)

    option = webdriver.ChromeOptions()
    option.add_argument('headless')

    driver.get("https://lbs.amap.com/tools/picker")

    # 等待页面加载完成
    wait = WebDriverWait(driver, 10)

    # 运行过程中验证时注释掉
    with open('经纬度.csv', 'w', newline='', encoding='utf-8') as f:
        csv_write = csv.writer(f)
        csv_write.writerow(['城市', '维度', '经度'])

    for search_name in data['城市']:
        if (search_name != ''):
            driver.find_element_by_xpath(
                '//*[@id="txtSearch"]').send_keys(search_name)
            time.sleep(random.randint(5, 20))
            driver.find_element_by_xpath(
                '//*[@id="myPageTop"]/table/tbody/tr[2]/td[1]/a').click()
            time.sleep(random.randint(5, 20))
            info = driver.find_element_by_xpath('//*[@id="txtCoordinate"]')
            company_info = info.get_attribute('value')
            time.sleep(random.randint(5, 20))
            driver.find_element_by_xpath(
                '//*[@id="txtSearch"]').clear()
            latitude = company_info.split(',')[1]
            longitude = company_info.split(',')[0]
            with open('经纬度.csv', 'a', newline='', encoding='utf-8') as f:
                csv_write = csv.writer(f)
                csv_write.writerow([search_name, latitude, longitude])


def get_result():
    # 读取CSV文件
    df = pd.read_csv('经纬度.csv', encoding='utf-8')

    company = pd.read_csv('公司.csv')

    # 新增一列
    df['公司名称'] = company['公司名称']

    # 保存到CSV文件
    df.to_csv('经纬度2.csv', index=False)


if __name__ == '__main__':
    # 获取公司名
    uni_name()

    # driver = webdriver.Chrome(options=option)  # 浏览器驱动,不打开浏览器运行
    driver = webdriver.Chrome("chromedriver.exe")  # 打开浏览器

    # 获取学校经纬度信息
    company_info_collect()

    # 关闭浏览器驱动
    driver.quit()

    # 将公司名写入csv
    get_result()

    # 最后再次去重
    data = pd.read_csv('经纬度2.csv', header=0, on_bad_lines='skip')
    data.drop_duplicates()  # 去除重复行
    data.to_csv('经纬度2.csv')


